package com.zrj.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关日志过滤器
 *
 * @author zrj
 * @since 2022/10/6
 **/
@Slf4j
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info( "【网关过滤器】请求接口：{}", JSONUtil.toJsonStr( exchange.getRequest() ) );

        String name = exchange.getRequest().getQueryParams().getFirst( "name" );
        if (StrUtil.isNotBlank( name )) {
            log.info( "日志过滤器，用户名bu为空." );
            exchange.getResponse().setStatusCode( HttpStatus.NOT_ACCEPTABLE );
            return exchange.getResponse().setComplete();
        }

        return chain.filter( exchange );
    }

    @Override
    public int getOrder() {
        return -30;
    }
}
